package ig.formato.util;

import ig.formato.gui.run.PrincipalIGFormato;
import java.io.File;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.view.JRSaveContributor;

public class JRXlsSaveContributor extends JRSaveContributor {

    @Override
    public void save(JasperPrint jp, File file) throws JRException {
        JRXlsExporter exporter = new JRXlsExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
        if(!file.getName().toLowerCase().trim().endsWith(".xls")){
            file=new File(file.getParentFile(), file.getName()+".xls");
        }
        if(file.exists() && JOptionPane.showConfirmDialog(null, "El archivo "+file.getName()+" ya existe. Desea reemplazarlo ? ", "", JOptionPane.OK_CANCEL_OPTION)!=0){
            return;
        }
        if(file.exists() && !file.canWrite() && !file.canRead()){
            JOptionPane.showMessageDialog(null, "El archivo "+file.getName()+" es de solo lectura. ", "", JOptionPane.YES_OPTION);
        }

        exporter.setParameter(JRExporterParameter.OUTPUT_FILE, file);
        exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        //exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.TRUE);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");

        try {
            exporter.exportReport();
        } catch (JRException jRException) {
            if (jRException.getCause() instanceof java.io.FileNotFoundException){
                JOptionPane.showMessageDialog(null, "El archivo "+file.getName()+" es de solo lectura.  ", "", JOptionPane.YES_OPTION);
            }else{
                throw jRException;
            }
        }
    }

    @Override
    public boolean accept(File f) {
        if(f.isDirectory()){
            return true;
        }else if ( f.getName().toLowerCase().trim().endsWith(".xls")){
            return true;
        }
        return false;
    }

    @Override
    public String getDescription() {
        return "Hoja de Calculo (*.xls)";
    }
}